using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace SPGE
{
    public class SimpleText : GameItem
    {
        public override string Path
        { get; protected set; }

        public Color Color
        { get; set; }

        public string Text
        { get; set; }

        public string CustomText
        { get; set; }

        public bool DropShadow
        { get; set; }

        SpriteFont font;

        public SimpleText(string path, string text)
            : base(SpriteBatchUse.AlreadyBeganSpriteBatch)
        { 
            Path = path;
            Scaling = Vector2.One;
            Text = text;
            CustomText = "";
            Color = Color.White;
            DropShadow = true;
        }

        public override void Initialize()
        {
        }

        public override void Load(ResourceGroupHandler group)
        {
            if (OnLoadStart != null)
                OnLoadStart(this);

            font = group.LoadItem<SpriteFont>(Path);
            
            Vector2 size;
            int count = 0;
            int lastIndex = 0;
            do
            {
                count++;
                int i = lastIndex;
                for (; i < Text.Length && Scaling.X * font.MeasureString(Text.Substring(lastIndex, i - lastIndex)).X <= Size.X; i++)
                    ;

                if (i < Text.Length)
                    Text = Text.Insert(i, "\n");

                lastIndex = i + 1;
            } while (Scaling.X * font.MeasureString(Text).X > Size.X && lastIndex > 0 && lastIndex <= Text.Length && count < 20);

            Size = font.MeasureString(Text);

            if (OnLoadEnd != null)
                OnLoadEnd(this);
        }

        public override void Unload()
        {
        }

        public override void Draw(Microsoft.Xna.Framework.GameTime gameTime, SpriteBatch spriteBatch)
        {
            if (OnRenderStart != null)
                OnRenderStart(this);

            var color = Color.ToVector4();
            color.W = Opacity;
            spriteBatch.DrawString(font, Text + CustomText, Position, new Color(color), Rotation, Origin * Size, Scaling, SpriteEffects.None, RenderLevel);
            if (DropShadow)
                spriteBatch.DrawString(font, Text + CustomText, Position + new Vector2(1.5f), new Color(0f, 0f, 0f, Opacity * 0.7f), Rotation, Origin * Size, Scaling, SpriteEffects.None, RenderLevel + 0.0000001f);

            if (OnRenderEnd != null)
                OnRenderEnd(this);

        }
    }
}
